package com.itheima.sevice.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.sevice.CheckItemService;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.exception.DeletionNotAllowedException;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemDao checkItemDao;

    @Autowired
    private CheckGroupDao checkGroupDao;

    /**
     * 添加检查项
     * @param checkItem
     * @return
     */
    @Override
    public Integer insert(CheckItem checkItem) {
        Integer recordCount = checkItemDao.insert(checkItem);
        return recordCount;
    }

    /**
     * 根据id删除检查项
     * @param id
     * @return
     */
    @Override
    public Integer deleteById(Integer id) {
        // 检查项和检查组有关联，则不能删除该检查项
        Integer count = checkItemDao.countByCheckItemId(id);
        if (count != null && count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DELETE_CHECKITEM_FAIL);
        }

        Integer recordCount = checkItemDao.deleteById(id);
        return recordCount;
    }

    /**
     * 根据检查组的id查询关联的检查项id
     * @param checkgroupId
     * @return
     */
    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer checkgroupId) {
        List<Integer> checkItemIds = checkGroupDao.findCheckItemIdsByCheckGroupId(checkgroupId);
        return checkItemIds;
    }

    /**
     * 编辑
     * @param checkItem
     * @return
     */
    @Override
    public Integer update(CheckItem checkItem) {
        Integer recordCount = checkItemDao.update(checkItem);
        return recordCount;
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<CheckItem> checkItemList = checkItemDao.pageQuery(queryPageBean);
        Page<CheckItem> p = (Page<CheckItem>) checkItemList;

        return new PageResult(p.getTotal(), p.getResult());
    }

    /**
     * 查询所有检查项
     * @return
     */
    @Override
    public List<CheckItem> findAll() {

        return checkItemDao.findAll();
    }

    /**
     * 根据id查询检查项
     * @param id
     * @return
     */
    @Override
    public CheckItem findById(Integer id) {
        CheckItem checkItem = checkItemDao.findById(id);

        return checkItem;
    }
}
